<?php

function bookkeep_data_invoices_by_user($UserId) {
	
	$data = array();
	
	$sql = '	
		SELECT 
			invoice.nid
		FROM
			{bk_Customer} contact
		INNER JOIN
			{content_type_bk_invoice} invoice ON invoice.field_invoice_companynode_nid = contact.nid
		WHERE 
			contact.uid = %s;
	';

	$db = db_query($sql, $UserId);
	
	while ($rec = db_fetch_object($db)) {
		$node = node_load($rec->nid);
		
		$companyNodeId = $node->field_invoice_companynode[0]['nid'];
		$companyNode = node_load($companyNodeId);
		$node->field_invoice_companynode[0]['value'] = $companyNode;
		
		array_push($data, $node);
	}

	return $data;
}

function bookkeep_data_company_list() {
	
	$data = array();
	
	$sql = '
		SELECT 
			n.nid
		FROM
			{node} n
		WHERE
			n.type = \'bk_company\';
	';
	
	$db = db_query($sql);
	
	while ($rec = db_fetch_object($db)) {
		$node = node_load($rec->nid);
		array_push($data, $node);
	}
	
	return $data;
}

function bookkeep_data_invoice_items($InvoiceId) {
	
	$data = array();
	
	$sql = '
		SELECT 
			n.nid 
		FROM 
			{node} n 
		INNER JOIN
			{content_type_bk_item} i ON i.nid = n.nid
		WHERE 
			n.type = \'bk_item\' AND
			i.field_invoicenode_nid = %s;
	';
	
	$db = db_query($sql, $InvoiceId);
	
	while ($rec = db_fetch_object($db)) {
		
		$node = node_load($rec->nid);
		array_push($data, $node);
	}
	
	return $data;
}

function bookkeep_data_current_invoices() {
	
	$data = array();
	
	$db = db_query("SELECT n.nid FROM {node} n where n.type = 'bk_invoice';");
	
	while ($rec = db_fetch_object($db)) {
		
		$node = node_load($rec->nid);
		
		$companyNodeId = $node->field_invoice_companynode[0]['nid'];
		$companyNode = node_load($companyNodeId);
		$node->field_invoice_companynode[0]['value'] = $companyNode;
		
		array_push($data, $node);
	}
	
	return $data;
}

function bookkeep_get_company_id($uid) {
	
	$intCompanyId = 0;
	$strSQL = "SELECT * FROM {bk_Customer} WHERE uid = %s";
	$db = db_query($strSQL, $uid);
	
	while ($rec = db_fetch_object($db)) {
		$intCompanyId = $rec->nid;
	}
	
	return $intCompanyId;
}

function bookkeep_get_user_invoice_access($uid, $nid) {
	
	$boolRtn = false;
	
	// Is the user an administer
	if(user_access('administer invoices') == true) {
		$boolRtn = true;
	}
	else {
		// Do they belong to the company
		$arrData = bookkeep_data_invoices_by_user($uid);
		
		foreach($arrData as $nodeInvoice) {
			if($nodeInvoice->nid == $nid) {
				$boolRtn = true;
			}
		}
	}
	
	return $boolRtn;
}

function bookkeep_data_save_customer($uid, $nid) {
	
	// Delete any previous items
	$strSQL = "DELETE FROM {bk_Customer} WHERE uid = %s;";
	db_query($strSQL, $uid);
	
	// Create a new record
	$strSQL = "INSERT INTO {bk_Customer} (uid, nid) VALUES (%s, %s);";
	db_query($strSQL, $uid, $nid);
}

?>